package com.liuzy;

import java.io.File;
import java.util.Iterator;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class ApkDecoder {
	public static void main(String[] args) throws Exception {
		File apk = new File("d:\\test\\sqfengchao.apk");
		decode(apk);
	}

	public static Result decode(File apk) throws Exception {
		File outDir = new File(apk.getParent() + File.separator + apk.getName().substring(0, apk.getName().lastIndexOf(".")));
		deleteDir(outDir);
		ApkTool apkTool = new ApkTool();
		apkTool.setOutDir(outDir);
		apkTool.setApkFile(apk);
		apkTool.decode();

		Result result = new Result();
		// 1.提取xml文件中的manifest里的attribute（android:versionName，package）
		SAXReader reader = new SAXReader();
		Document doc = reader.read(outDir + File.separator + "AndroidManifest.xml");
		Element root = doc.getRootElement();
		String version = root.attributeValue("versionName");
		if (version == null) {
			File yml = new File(outDir + File.separator + "apktool.yml");
			Scanner scanner = new Scanner(yml);
			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				if (line != null && line.contains("versionName")) {
					version = line.trim().replace("versionName", "").replace(": ", "").replaceAll("\'", "");
					break;
				}
			}
			scanner.close();
		}
		result.setVersion(version);
		result.setPackageName(root.attributeValue("package"));
		String label = null;
		Element child = null;
		// 2.提取xml文件中的manifest/application里的attribute（android:label，android:icon）
		for (Iterator<?> i = root.elementIterator("application"); i.hasNext();) {
			child = (Element) i.next();
			label = child.attributeValue("label"); // 得到application里的android:label
		}
		// 如果android:label="@string/******"，那去\res\values目录下的strings.xml文件中，取******中的TEXT；
		String newLabel = label.substring(label.lastIndexOf("/") + 1, label.length());
		// SAXReader sreader = new SAXReader();
		Document sdoc = null;
		File resFile = new File(outDir + File.separator + "res");
		String[] resFiles = resFile.list();
		boolean flag = false;
		if (resFiles != null && resFiles.length > 0) {
			for (String str : resFiles) {
				if ("values-zh-rCN".equals(str)) {
					flag = true;
					break;
				}
			}
		}
		if (flag)
			sdoc = reader.read(outDir + File.separator + "res" + File.separator + "values-zh-rCN" + File.separator + "strings.xml");
		else
			sdoc = reader.read(outDir + File.separator + "res" + File.separator + "values" + File.separator + "strings.xml");
		String xpath = "//string[@name=\'" + newLabel + "\']";
		// 搜索string.xml中name为"newLabel"的节点
		Node n = sdoc.selectSingleNode(xpath);
		Node n1 = null;
		// 如果在values-zh-rCN中的string.xml没有找到匹配的则在values中的string.xml搜索
		if (n == null) {
			sdoc = reader.read(outDir + File.separator + "res" + File.separator + "values" + File.separator + "strings.xml");
			n1 = sdoc.selectSingleNode(xpath);
			if (n1 == null) {
				result.setAppName(label);
			} else {
				if (n1.getText().startsWith("@")) {
					String newLabel1 = n1.getText().substring(n1.getText().lastIndexOf("/") + 1, n1.getText().length());
					n1 = sdoc.selectSingleNode("//string[@name=\'" + newLabel1 + "\']");
				}
				result.setAppName(n1.getText());
			}
			if (version.startsWith("@")) {
				String newver = version.substring(version.lastIndexOf("/") + 1, version.length());
				n1 = sdoc.selectSingleNode("//string[@name=\'" + newver + "\']");
				result.setVersion(version);
			}
		} else {
			if (n.getText().startsWith("@")) {
				String newLabel1 = n.getText().substring(n.getText().lastIndexOf("/") + 1, n.getText().length());
				n = sdoc.selectSingleNode("//string[@name=\'" + newLabel1 + "\']");
			}
			result.setAppName(n.getText());
			if (version.startsWith("@")) {
				String newver = version.substring(version.lastIndexOf("/") + 1, version.length());
				n1 = sdoc.selectSingleNode("//string[@name=\'" + newver + "\']");
				result.setVersion(version);
			}
		}
		deleteDir(outDir);
		System.out.println(result);
		return result;
	}

	private static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		return dir.delete();
	}
}
